package event;

import java.io.File;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Enter {
    private static String dataFrom;
    private static String topic;
    private static String timeBegin;
    private static String timeEnd;
    private static String server;
    private static String groupId;
    private static int[] eventType;
    private static int cellIndex;

    private static StringBuilder matchResult = new StringBuilder();


    private static String helpInfo = "" +
//            " dataFrom=/Users/huit/ad-event.txt" +
//            " dataFrom=/Users/huit/work/ad-parse/超杀默示录0516~0522/超杀默示录-20180522-14038.xls" +//文件或目录
            " dataFrom=/Users/huit/work/ad-parse/0601/极无双-0530-5573.xlsx" +//文件或目录
//            " dataFrom=/Users/huit/work/ad-parse.xlsx" +//*.xlsx *.xls
            " topic=TOPIC_SDK_CN_BIND_PHONE" +
//            " timeBegin=2018-05-15-00:00:00" +//开始时间，可选
//            " timeEnd=2018-05-15-15:00:00" +//结束时间，可选
            " server=10.0.6.200:9092,10.0.6.200:9093,10.0.6.200:9094" +
            " groupId=adEventParse" +
            " cellIndex=0" +
            " eventType=1,2,3" +
            "";


    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            args = helpInfo.split(" ");//test
            System.out.println("paramError helpInfo->java -jar ad-parse-jar-with-dependencies.jar " + helpInfo);
//            return;
        }
        parseArgs(args, Enter.class, "helpInfo,matchResult".split(","));
        parseFile(new File(dataFrom));
        System.out.println(matchResult);
    }

    private static void parseFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File file1 : files) {
                parseFile(file1);
            }
        } else {
            match(file);
        }
    }

    private static void match(File file) {
        if (!file.isFile() || file.getName().endsWith("matched")) {
            return;
        }
        long beginTime = System.currentTimeMillis();

        ImportExcel importExcel = new ImportExcel();
        Set<String> formMatch;
        if (file.getName().endsWith(".xlsx") || file.getName().endsWith(".xls")) {
            formMatch = importExcel.read(file.getPath(), cellIndex);
        } else {
            formMatch = FileReAndWrUtil.readFile(file);
        }

        System.out.println("开始匹配 fileName:" + file.getName() + " loadDataSize:" + formMatch.size());
        long start, end;
        if (null == timeBegin && null == timeEnd) {
            Pattern pattern = Pattern.compile("-([0-9]*)");
            Matcher date = pattern.matcher(file.getName());
            if (!date.find()) {
                System.out.println("日期格式错误：" + file.getName());
                return;
            }
            String time = date.group(1);
            if (time.length() == 4) {
                time = Calendar.getInstance().get(Calendar.YEAR) + time;
            }
            start = getUnixTime(time);
            end = start + 24 * 3600 * 1000;
        } else {
            start = getUnixTime(timeBegin);
            end = getUnixTime(timeEnd);
        }

        //获得包含的数据
        Set<String> setWhichIsContained = new KafkaProducerUtil().getMsg(server, groupId, topic, start, end, formMatch, eventType);
        //写出成txt
        File file2 = new File(file.getPath() + ".matched");
        FileReAndWrUtil.writeFile(file2, setWhichIsContained);
        String msg = "文件名:" + file.getName() + " 广告商提供数据条数:" + formMatch.size() + " 匹配成功:" + setWhichIsContained.size()
                + " 开始时间:" + start + " 结束时间:" + end + " 匹配耗时:" + (System.currentTimeMillis() - beginTime);
        matchResult.append(msg).append("\r\n");
        System.out.println(msg);
    }

    public static long getUnixTime(String value) {
        return getUnixTime(value, null);
    }

    private static String[] datePatten = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd-HH:mm:ss", "yyyyMMddHHmmss", "yyyy-MM-dd", "yyyyMMdd"};


    public static long getUnixTime(String value, String patten) {
        Date date = null;
        if (null != patten) {
            DateFormat df = new SimpleDateFormat(patten);
            try {
                date = df.parse(value);
            } catch (ParseException e) {
            }
        } else {
            for (String s : datePatten) {
                DateFormat df = new SimpleDateFormat(s);
                try {
                    date = df.parse(value);
                    break;
                } catch (ParseException e) {
                }
            }
        }
        if (null != date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            return cal.getTimeInMillis();
        }
        return -1;
    }

    /**
     * 解析入参
     *
     * @param args
     * @param class_
     * @param excludesParm @throws Exception
     */
    private static void parseArgs(String[] args, Class class_, String[] excludesParm) throws Exception {
        if (args == null || args.length == 0) {
            System.exit(1);
        }
        for (String arg : args) {
            int index = arg.indexOf('=');
            if (index < 0) {
                continue;
            }
            String key = arg.substring(0, index);
            String value = arg.substring(index + 1);


            Field field = null;
            try {
                field = Enter.class.getDeclaredField(key);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            if (field.getType() == String.class) {
                field.set(key, value);
            } else if (field.getType().getName().equals("[Ljava.lang.String;")) {
                field.set(key, value.split(","));
            } else if (field.getType().getName().equals("boolean")) {
                field.set(key, Boolean.parseBoolean(value));
            } else if (field.getType().getName().equals("int")) {
                field.set(key, Integer.parseInt(value));
            } else if (field.getType().getName().equals("[I")) {
                String[] str = value.split(",");
                int[] intValue = new int[str.length];
                for (int i = 0; i < intValue.length; i++) {
                    intValue[i] = Integer.valueOf(str[i]);
                }
                field.set(key, intValue);
            } else if (field.getType().getName().equals("long")) {
                field.set(key, Long.parseLong(value));
            } else if (field.getType().getName().equals("java.util.Map")) {
                Map map = new HashMap();
                for (String s : value.split(",")) {
                    String[] kv = s.split("->");
                    if (kv.length != 2) {
                        System.err.println("参数错误：" + s);
                        System.exit(0);
                    }
                    map.put(kv[0], kv[1]);
                }
                field.set(key, map);
            } else {
                System.out.println("unKnowType->" + field.getName() + ":" + field.getType());
            }
        }

        Field[] fields = class_.getDeclaredFields();
        for (Field field : fields) {
            boolean isExclude = false;
            for (String s : excludesParm) {
                if (s.equals(field.getName())) {
                    isExclude = true;
                    break;
                }
            }
            if (!isExclude) {
                Object value = null;
                String name = field.getType().getName();
                if (name.equals("[Ljava.lang.String;")) {
                    Object[] values = (Object[]) field.get(field.getName());
                    if (null != values && values.length > 0) {
                        value = Arrays.toString(values);
                    }
                } else if (name.equals("[I")) {
                    int[] values = (int[]) field.get(field.getName());
                    if (null != values && values.length > 0) {
                        value = Arrays.toString(values);
                    }
                } else {
                    value = field.get(field.getName());
                }
                if (value == null) {
                    value = "";
                }
                System.out.println(field.getName() + "->" + value);
            }
        }
    }
}
